package com.xigege.netty.webSocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class MyServer {
    public static void main(String[] args) throws Exception{
        //创建两个线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) //在bossGroup增加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //因为是基于http协议，使用http的编码解码器
                            pipeline.addLast(new HttpServerCodec());

                            //是以块方式写，添加ChunkedWriteHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());

                            //说明：
                            //1.http数据在传输过程中是分段的，HttpObjectAggregator就是可以将多个段聚合起来
                            //2.这就是为啥子当浏览器大量数据时，就会发送多次http请求
                            pipeline.addLast(new HttpObjectAggregator(8192));

                            //说明：
                            //1.对于webSocket，他的数据是以帧（frame）的形式传递的
                            //2.可以看到WebSocketFrame下面有六个子类(可以用这些不同帧的形式进行数据传递)
                            //3.浏览器请求时：ws://localhost:7000/xxx 表示请求的uri，
                            //      /xxx 与WebSocketServerProtocolHandler里面配置的websocketPath对应才能进行长连接
                            //4.WebSocketServerProtocolHandler核心功能是将http协议升级为ws协议，即webSocket保持长连接
                            //      是通过一个状态码 101
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

                            //自定义的handler，处理浏览器请求，即业务逻辑
                            pipeline.addLast(new MysServerHandler());
                    }
                    });
            //启动服务器,绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();

            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
